<template>
  <div style="margin: 0px 20px; overflow: hidden">
    <el-form :model="form" :rules="rules" ref="form" label-position="top" label-width="80px">
      <el-form-item :label="$t('public.name')" prop="displayName">
        <el-input v-model.trim="form.displayName" :placeholder="$t('agentSetting.agentSetting57')" size="mini"></el-input>
      </el-form-item>
      <el-form-item :label="$t('public.jobNumber')" prop="exten">
        <el-input v-model.trim="form.exten" :disabled="isEditExten" :placeholder="$t('config.agent.pleaseExten')" size="mini" @blur="changeJobNum"></el-input>
        <div v-if="isShowTip" class="tip-color">{{$t('agentSetting.agentSetting58')}}</div>
      </el-form-item>
      <el-form-item :label="$t('config.agent.phoneNumber')" prop="mobile">
        <el-input v-model.trim="form.mobile" :placeholder="$t('config.agent.pleasePhone')" size="mini"></el-input>
      </el-form-item>
      <el-form-item :label="$t('public.email')">
        <el-input v-model.trim="form.ivrInfo.email" :placeholder="$t('config.agent.pleaseEmail')" size="mini"></el-input>
      </el-form-item>
      <el-form-item :label="$t('public.nickName')">
        <el-input v-model.trim="form.nickName" auto-complete="off" :placeholder="$t('agentSetting.agentSetting3')" size="mini"></el-input>
        <span class="tip">
                <el-tooltip
                  transition="fade-leave"
                  effect="dark"
                  :content="$t('public.nickNameTip')"
                  placement="bottom">
                  <i class="icon iconfont icon-tixingweizhi"></i>
                </el-tooltip>
              </span>
      </el-form-item>
      <el-form-item :label="$t('public.password')">
        <el-input readonly onfocus="this.removeAttribute('readonly')" autocomplete='new-password' v-model.trim="form.ivrInfo.password" :placeholder="$t('config.agent.pleasePassword')" type = "password" size="mini"></el-input>
        <div class="recommended-pwd">{{$t('agentSetting.agentSetting4')}}:{{recommendedPwd}}</div>
      </el-form-item>
      <el-form-item :label="$t('agentSetting.agentSetting5')">
        <el-select v-model="form.uversion" size = "mini" :disabled="isUversion">
          <el-option
            v-for="item in Package"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('config.agent.modifyRole')" prop="role">
        <el-select class="select"
                   v-model="form.role"
                   multiple
                   collapse-tags
                   size="mini"
                   filterable>
          <el-option v-for="item in optionsStatus"
                     :label="item.label"
                     :key="item.value"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="'修改座席接待会话范围'">
        <el-select v-model.trim="form.minImDealCount" size="mini" style="width: 130px">
          <el-option
            v-for="item in minNumber"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <span style="margin: 0px 10px">--</span>
        <el-select v-model.trim="form.maxImDealCount" size="mini" style="width: 140px">
          <el-option
            v-for="item in maxNumber"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="批量修改在线咨询自动领取">
        <el-switch v-model="form.imClaimStatus"></el-switch>
      </el-form-item>
    </el-form>
    </div>
</template>
<script>
  import {checkform} from '@/utils/validate'
  import AgentSelect from '@/components/public-modules/cache/AgentSelect'
  import Roles from '@/components/public-modules/cache/Roles'
  import { deepClone, isHasMenu } from '@/utils/m7Utils.js'
  export default {
    name: 'EditAgent',
    data () {
      let validate1 = (rule, value, callback) => {
        if (value === '') {
//          this.isShowTip = false
          callback(new Error(this.$t('validate.required')))
        } else if (checkform(value, 'Number')) {
//          this.isShowTip = false
          callback(new Error(this.$t('customer.shouldBeNumber')))
        } else {
//          this.isShowTip = true
          callback()
        }
      }
      let validate2 = (rule, value, callback) => {
        if (checkform(value, 'Number')) {
          callback(new Error(this.$t('customer.shouldBeNumber')))
        } else {
          callback()
        }
      }
      return {
        optionsStatus: [],
        isEditExten: false,
        oldExten: '',
        isShowTip: false,
        isInherit: false, // 是否为附属工号
        recommendedPwd: '', // 推荐密码
        maxNumber: [], // 渲染座席最大能同时接待会话下拉
        minNumber: [], // 渲染座席最小能同时接待会话下拉
        Package: [], // 座席使用版本渲染数据
        isIvrInfo: false, // 判断是否传IvrInfo
        cloneIvrInfo: {}, // 和之前IvrInfo对比用
        form: {
          nickName: '', // 昵称
          _id: '',  // 当前座席id
          deptId: '', // 部门id
          role: [], // 角色id数组
          imClaimStatus: 'open', // 在线咨询自动领取开关
          maxImDealCount: '', // 最大能同时接待会话
          minImDealCount: '', // 最小能同时接待会话
          displayName: '', // 姓名
          uversion: '', // 座席使用版本
          exten: '', // 工号
          mobile: '', // 电话
          ivrInfo: {
            _id: '',
            displayName: '',
            exten: '',
            mobile: '',
            email: '',
            uversion: '',
            type: '', // 是否为监控座席
            password: ''
          }
        },
        rules: { // 饿了么校验规则
          displayName: [
            { required: true, message: this.$t('config.agent.pleaseName'), trigger: 'blur' }
          ],
          exten: [
            { required: true, validator: validate1, trigger: 'blur' }
          ],
          mobile: [
            { validator: validate2, trigger: 'blur' }
          ],
          role: [
            { required: true, message: this.$t('config.agent.pleaseRole'), type: 'array' }
          ]
        }
      }
    },
    props: {
      agentDetail: Object // 座席信息
    },
    computed: {
      isUversion () { // 判断是不是计费跳转 是则可修改版本
        if (this.$store.state.session.user.type !== 'admin' && this.$store.state.session.user.exten !== '0000') {
          return true
        } else {
          return false
        }
      }
    },
    watch: {
    },
    components: {
      AgentSelect,
      Roles
    },
    methods: {
      resetForm () {
        this.$refs['form'].clearValidate()
      },
      changeJobNum () {
        let that = this
        if (that.form.exten !== that.oldExten) {
          that.isShowTip = true
        } else {
          that.isShowTip = false
        }
      },
      randomWord (min, max) {
        let str = ''
        let range = min
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        // 随机产生
        range = Math.round(Math.random() * (max - min)) + min
        for (let i = 0; i < range; i++) {
          let pos = Math.round(Math.random() * (arr.length - 1))
          str += arr[pos]
        }
        return str
      },
      updatePwd () {
        let _pattern = '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$'
        let _pwd = this.randomWord(8, 11)
        while (!_pwd.match(_pattern)) {
          _pwd = this.randomWord(8, 11)
        }
        let teStr = '#_!'
        let _numRan = Math.floor(Math.random() * 4)
        let _arrayStr = _pwd.split('')
        _arrayStr.splice(_numRan, 0, teStr.charAt(_numRan))
        this.recommendedPwd = _arrayStr.join('')
      },
      // 渲染套餐类型字段
      showPackage () {
        let Packages = this.$getCache('licenceType')
        Packages.map(item => {
          this.Package.push({
            label: item.code_name,
            value: item.code_value
          })
        })
      },
      onSubmit () {
        // 声明正整数校验规则
        if (parseInt(this.form.minImDealCount) > parseInt(this.form.maxImDealCount)) {
          this.$message.error(this.$t('config.agent.imDealErroTip'))
          return
        }
        // 判断角色是否为空
        // 表单校验
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 成功执行
            let data = deepClone(this.form)
            // 判断工号
            if (data.exten.length !== 4 && data.exten.length !== 5) {
              this.$message.error(this.$t('agentSetting.agentSetting63'))
              return
            } else if (data.exten.length === 4 && (data.exten.substring(0, 1) === '0' || data.exten.substring(0, 1) === '9')) {
              this.$message.error(this.$t('agentSetting.agentSetting64'))
              return
            } else if (data.exten.length === 5 && (data.exten.substring(0, 1) === '0' || data.exten.substring(0, 1) === '9' || data.exten.substring(0, 1) === '1')) {
              this.$message.error(this.$t('agentSetting.agentSetting65'))
              return
            }
            // if (data.exten && (data.exten.length !== 4 || data.exten.substring(0, 1) === '0' || data.exten.substring(0, 1) === '9')) {
            //   this.$message.error(this.$t('config.agent.extenErroMessage'))
            //   return
            // }
            // 密码校验
            let passwordNew = data.ivrInfo.password
            if (passwordNew !== null && passwordNew !== '') {
              let regexPass = false
              let lengthRegex = new RegExp('^.{8,}$') // >= 8位
              let characterRegex = new RegExp('[a-z]') // 小寫
              let characterRegex2 = new RegExp('[A-Z]') // 大寫
              let numberRegex = new RegExp('[0-9]')// 數字
              let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
              let num = 0
              let temporary = data.ivrInfo.password
              temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
              if (characterRegex.test(passwordNew)) {
                num += 1
              }
              if (characterRegex2.test(passwordNew)) {
                num += 1
              }
              if (numberRegex.test(passwordNew)) {
                num += 1
              }
              if ((passwordNew.length - temporary.length) > 0) {
                num += 1
              }
              if (num >= 3) {
                regexPass = true
              } else {
                regexPass = false
              }
              if (!lengthRegex.test(passwordNew)) {
                regexPass = false
              }
              if (chinese.test(passwordNew)) {
                regexPass = false
              }
              let limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
              for (let i = 0; i < limitArr.length; i++) {
                if (passwordNew.indexOf(limitArr[i]) > -1) {
                  regexPass = false
                  break
                }
              }
              if (!regexPass) {
                this.$message.error(this.$t('config.agent.newPasswordRule'))
                return
              }
            }
            // 给data.ivrInfo的校验字段赋值
            data.ivrInfo.displayName = data.displayName
            data.ivrInfo.mobile = data.mobile
            data.ivrInfo.exten = data.exten
            data.ivrInfo.uversion = data.uversion
            delete data.uversion
            delete data.displayName
            delete data.mobile
            delete data.exten
            // 判断是否需改了displayName, mobile, exten, uversion 这几个字段，如果修改了就传
            for (let key in this.cloneIvrInfo) {
              if (this.cloneIvrInfo[key] !== data.ivrInfo[key]) {
                this.isIvrInfo = true
              }
            }
            // 如果密码为空不传密码项
            data.ivrInfo.password === '' && delete data.ivrInfo.password
            if (!this.isIvrInfo) {
              delete data.ivrInfo
            } else {
              if (this.isUversion) {
                data.ivrInfo.uversion && delete data.ivrInfo.uversion
              }
            }
            this.isIvrInfo = false
            console.log(data)
            console.log('edit-----agent')
            this.$emit('EditAgent', data)
          }
        })
      },
      getRoleIds (arr) {
        let ids = []
        arr.map(item => {
          ids.push(item.value)
        })
        return ids
      },
      deptChange (deptId) {
        this.form.deptId = deptId
      },
      agentChange (parentId) {
        this.form.parentId = parentId
      },
      // 循环座席能同时接待会话数
      forNumber (num, obj) {
        for (let i = 1; i < num + 1; i++) {
          obj.push({
            label: i + '',
            value: i + ''
          })
        }
      },
      // 避免后端没有返回字段
      dealType (basicType) {
        return basicType === undefined ? true : basicType
      },
      // 出始化修改详情
      init () {
        this.isShowTip = false
        this.rolesId = this.agentDetail.role
        this.form.role = this.agentDetail.role
        this.form.nickName = this.agentDetail.nickName || ''
        this.form._id = this.agentDetail._id
        this.form.imClaimStatus = this.agentDetail.imClaimStatus === undefined ? 'open' : this.agentDetail.imClaimStatus
        this.form.maxImDealCount = this.agentDetail.maxImDealCount
        this.form.minImDealCount = this.agentDetail.minImDealCount
        this.form.deptId = this.agentDetail.deptId
        this.form.parentId = this.agentDetail.parentId
        this.form.displayName = this.agentDetail.displayName
        this.oldExten = deepClone(this.agentDetail.exten)
        this.form.exten = this.agentDetail.exten
        this.form.mobile = this.agentDetail.mobile
        this.form.uversion = this.agentDetail.uversion
        this.form.ivrInfo.password = ''
        this.form.ivrInfo._id = this.agentDetail._id
        this.form.ivrInfo.email = this.agentDetail.email
        this.form.ivrInfo.type = this.agentDetail.type
        this.form.ivrInfo.displayName = this.agentDetail.displayName
        this.form.ivrInfo.mobile = this.agentDetail.mobile
        this.form.ivrInfo.exten = this.agentDetail.exten
        this.form.ivrInfo.uversion = this.agentDetail.uversion
        this.form.inheritedFrom = this.agentDetail.inheritedFrom
        this.cloneIvrInfo = deepClone(this.form.ivrInfo)
        this.inheritAgent = ''
        this.isInherit = false
      }
    },
    beforeMount () {
      this.forNumber(200, this.maxNumber)
      this.forNumber(50, this.minNumber)
      this.$store.dispatch('getCache', {type: 'roles'}).then((res) => {
        let rolesArray = roleMessage(res)
        this.optionsStatus = [...rolesArray]
      })
      this.showPackage()
      if (isHasMenu('func_not_allow_edit_agent_exten', this.$store.state.session.user) || this.$store.state.session.user.isAdmin) {
        this.isEditExten = true
      }
    }
  }
  function roleMessage (roles) {
    let arrRole = []
    roles.map((item) => {
      arrRole.push({
        label: item.display_name,
        value: item._id
      })
    })
    return arrRole
  }
</script>
<style lang="stylus" scoped>
@import "../../../../../../assets/common.styl"
  .tip-color
    color $c-pink
    font-size 12px
    bottom: -10px
    line-height normal
    position absolute
  .el-select
    width 100%
  .unbind
    color $c-email
    cursor pointer
  .bind_font
    font-size 12px
  .el-input
    font-size 12px
  .el-form-item
    margin-top 10px
  .search
    text-align center
  .recommended-pwd
    font-size 12px
  .tip
    position absolute
    top 10px
    cursor pointer
    display inline-block
    height 16px
    width 16px
    border 1px solid $c-main
    text-align center
    line-height 15px
    border-radius 50%
    margin 0px 0 0 6px
    .iconfont
      border none
      font-size 10px
      color $c-main
</style>
